package com.ermax.aircond.maintain.web.bean;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedProperty;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.ermax.aircond.maintain.domain.Building;
import com.ermax.aircond.maintain.domain.Floor;
import com.ermax.aircond.maintain.domain.Machine;
import com.ermax.aircond.maintain.domain.Room;
import com.ermax.aircond.maintain.service.MaintainService;
import com.ermax.aircond.resource.MessageBundle;
import com.ermax.aircond.util.web.bean.DataTableBean;

@Scope("view")
@Component
public class MachineMaintainBean extends DataTableBean implements java.io.Serializable {

	private static final long serialVersionUID = 1L;

	private static final Logger logger = LoggerFactory.getLogger(MachineMaintainBean.class);
	@Autowired
	private MaintainService maintainService;	
	@ManagedProperty(value = "#{loginBean.sessionUser}")
	private String sessionUser;

	private Machine editedItem;
	private List<Machine> machines = new ArrayList<Machine>();
	private List<SelectItem> buildingOptions = new ArrayList<SelectItem>();
	private List<SelectItem> floorOptions = new ArrayList<SelectItem>();
	private List<SelectItem> roomOptions = new ArrayList<SelectItem>();
	private long selectedBuildingId;
	private long selectedFloorId;
	private long selectedRoomId;

	@PostConstruct
	public void init() {
		try {			
			reset();
		} catch (Exception ex) {
			String message = MessageBundle.getInstance().getMessage("error_init_fail", FacesContext.getCurrentInstance().getViewRoot().getLocale());
			FacesMessage facesMessage = new FacesMessage(message);
			FacesContext.getCurrentInstance().addMessage(null, facesMessage);
		}
	}

	private void reset() throws Exception {		
		machines = maintainService.getMachines();
		buildingOptions = createBuildingOptions();
		floorOptions = createFloorOptions();
		roomOptions = createRooomOptions();
		editedItem = new Machine();
	}
		
	private List<SelectItem> createBuildingOptions() {
		List<SelectItem> results = new ArrayList<SelectItem>();		
		try {
			List<Building> buildings = maintainService.getAllBuildings();
			for (Building building : buildings) {
				SelectItem item = new SelectItem(building.getBuildingId(), building.getBuildingName());
				results.add(item);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}

		return results;
	}
	
	private List<SelectItem> createFloorOptions(){		
		List<SelectItem> results = new ArrayList<SelectItem>();		
		if(selectedBuildingId == 0){
			if(buildingOptions.size() > 0){
				SelectItem buildingItem = buildingOptions.get(0);
				selectedBuildingId = (Long) buildingItem.getValue();
			}
		}
		try{
			Building selectedBuilding = maintainService.getBuildingById(selectedBuildingId);
			List<Floor> floors = maintainService.getFloors(selectedBuilding);
        	for(Floor floor : floors){
        		SelectItem item = new SelectItem(floor.getFloorId(), floor.getFloorName());
        		results.add(item);
        	}
		}catch (Exception e) {
			logger.error(e.getMessage());
		}			
		return results;		
	}
	
	private List<SelectItem> createRooomOptions(){
		List<SelectItem> results = new ArrayList<SelectItem>();
		if(selectedFloorId == 0){
			if(floorOptions.size() > 0){
				SelectItem floorItem = floorOptions.get(0);
				selectedFloorId = (Long) floorItem.getValue();
			}
		}
		try{
			Floor selectedFloor = maintainService.getFloorById(selectedFloorId);
			List<Room> rooms = maintainService.getRooms(selectedFloor);
			for(Room room : rooms){
				SelectItem item = new SelectItem(room.getRoomId(), room.getRoomName());
				results.add(item);
			}
		}catch(Exception e){
			logger.error(e.getLocalizedMessage());
		}
		return results;
	}
	
	public void buildingValueChanged(ValueChangeEvent event) {      
        if (null != event.getNewValue()) {            
        	selectedFloorId = 0;
        	selectedRoomId = 0;
            selectedBuildingId = (Long) event.getNewValue();            
            floorOptions = createFloorOptions();
            roomOptions = createRooomOptions();
        }
    }
	
	public void floorValueChanged(ValueChangeEvent event) {      
        if (null != event.getNewValue()) {  
        	selectedRoomId = 0;
            selectedFloorId = (Long) event.getNewValue();
            roomOptions = createRooomOptions();
        }
    }

	public void create() {
		try {	
			Room room = maintainService.getRoomById(selectedRoomId);					
			editedItem.setRoom(room);
			maintainService.createMachine(editedItem, sessionUser);
			reset();
		} catch (Exception ex) {
			String message = MessageBundle.getInstance().getMessage("error_create_fail", FacesContext.getCurrentInstance().getViewRoot().getLocale());
			FacesMessage facesMessage = new FacesMessage(message);
			FacesContext.getCurrentInstance().addMessage(null, facesMessage);
		}
	}

	public void update() {
		try {			
			Room room = maintainService.getRoomById(selectedRoomId);					
			editedItem.setRoom(room);
			maintainService.updateMachine(editedItem, sessionUser);
			reset();
		} catch (Exception ex) {
			String message = MessageBundle.getInstance().getMessage("error_delete_fail", FacesContext.getCurrentInstance().getViewRoot().getLocale());
			FacesMessage facesMessage = new FacesMessage(message);
			FacesContext.getCurrentInstance().addMessage(null, facesMessage);
		}
	}

	public void remove() {
		try {
			Machine machine = machines.get(getCurrentIndex());
			maintainService.deleteMachine(machine);
			reset();
		} catch (Exception ex) {
			String message = MessageBundle.getInstance().getMessage("error_remove_fail", FacesContext.getCurrentInstance().getViewRoot().getLocale());
			FacesMessage facesMessage = new FacesMessage(message);
			FacesContext.getCurrentInstance().addMessage(null, facesMessage);
		}
	}
	
	public void search() {
		try{
			Building building = null;
			Floor floor = null;
			Room room = null;
			if(selectedBuildingId > 0){
				building = maintainService.getBuildingById(selectedBuildingId);
			}
			if(selectedFloorId > 0){
				floor = maintainService.getFloorById(selectedFloorId);
			}
			if(selectedRoomId > 0){
				room = maintainService.getRoomById(selectedRoomId);
			}
			machines = maintainService.getMachines(building, floor, room, getSearchStr());
		}catch(Exception ex){}
	}	

	public MaintainService getMaintainService() {
		return maintainService;
	}

	public void setMaintainService(MaintainService maintainService) {
		this.maintainService = maintainService;
	}

	public Machine getEditedItem() {
		return editedItem;
	}

	public void setEditedItem(Machine editedItem) {
		this.editedItem = editedItem;
	}

	public List<Machine> getMachines() {
		return machines;
	}

	public void setMachines(List<Machine> machines) {
		this.machines = machines;
	}

	public List<SelectItem> getBuildingOptions() {
		return buildingOptions;
	}

	public void setBuildingOptions(List<SelectItem> buildingOptions) {
		this.buildingOptions = buildingOptions;
	}

	public List<SelectItem> getFloorOptions() {
		return floorOptions;
	}

	public void setFloorOptions(List<SelectItem> floorOptions) {
		this.floorOptions = floorOptions;
	}

	public List<SelectItem> getRoomOptions() {
		return roomOptions;
	}

	public void setRoomOptions(List<SelectItem> roomOptions) {
		this.roomOptions = roomOptions;
	}

	public long getSelectedBuildingId() {
		return selectedBuildingId;
	}

	public void setSelectedBuildingId(long selectedBuildingId) {
		this.selectedBuildingId = selectedBuildingId;
	}

	public long getSelectedFloorId() {
		return selectedFloorId;
	}

	public void setSelectedFloorId(long selectedFloorId) {
		this.selectedFloorId = selectedFloorId;
	}

	public long getSelectedRoomId() {
		return selectedRoomId;
	}

	public void setSelectedRoomId(long selectedRoomId) {
		this.selectedRoomId = selectedRoomId;
	}
	

}
